//
//  DropDownMenu.swift
//  mggz
//
//  Created by 匀视网Mac on 2018/1/8.
//  Copyright © 2018年 爱丽丝的梦境. All rights reserved.
//

import UIKit
import MJRefresh
class DropDownMenu: UIView {
    /*
     menu 的table 和 内容
     */
    var menuTab: UITableView?
    var tableviewHeight:CGFloat? = 0
    let cellIdentifier = "cellID"
    fileprivate var currentPage = 1
    fileprivate weak var _loadingView: V2LoadingView?
    /*
     menu 选中行的方法
     */
    var didSelectIndex:((_ model:LCProjectListModel)->Void)?
    /*
     加载动画效果
     */
    var isShow : Bool?
    var menuSize : CGSize?
    lazy var itemArray : [LCProjectListModel] = [LCProjectListModel]()
    class func initDropDownMenu(size:CGSize)->DropDownMenu{
        
        let frame = CGRect(x:0,y:0,width:size.width,height:size.height)
        let menu = DropDownMenu.init(frame:frame)
        menu.menuSize = size
        return menu
    }
    
    
    override init(frame: CGRect) {
        
        /**
         这时候 frame 的 height 设置为 0 ，是为了加载缓慢弹出的动画……
         */
        let  initialFrame = CGRect(x:frame.origin.x,y:frame.origin.y,width:frame.size.width,height:0.0)
        
        super.init(frame: initialFrame)
        self.backgroundColor = UIColor.black
        self.layer.borderWidth = 1
        self.layer.cornerRadius = 5
        self.layer.masksToBounds = true
        self.layer.borderColor = UIColor(red: 0.91, green: 0.91, blue: 0.91, alpha: 0.91).cgColor
        self.getProjectListData()
        menuTab = UITableView.init(frame: CGRect(x:0,y:0,width:frame.size.width,height:0), style: .plain)
       // menuTab?.tableFooterView = UIView.init()
        menuTab?.delegate = self
        menuTab?.dataSource = self
        menuTab?.separatorStyle = .none
        addSubview(menuTab!)
        menuTab?.register(UINib.init(nibName: "LCProjectCell", bundle: nil), forCellReuseIdentifier: "LCProjectCell")
        menuTab?.isHidden = true
        isHidden = true
        isShow = false
        
        let tableHeader = MJRefreshNormalHeader { [unowned self] in
            self.getProjectListData()
        }
        tableHeader?.stateLabel.isHidden = true
        menuTab?.mj_header = tableHeader
        
        let tableFooter = MJRefreshAutoNormalFooter { [unowned self] in
            self.getNextPage()
        }
        menuTab?.mj_footer = tableFooter
        
        menuTab?.mj_header.beginRefreshing()
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    private func getProjectListData(){
        self.currentPage = 1
        //WWProgressHUD.showWithStatus("正在载入数据...")
        ProjectListNetWork.projectList(pageIndex: self.currentPage, pageSize: 25, keyword: "", isShowApplying: false) { (response) in
            //WWProgressHUD.dismiss()
            if response.success {
                self.itemArray = response.value!
                self.menuTab?.reloadData()
            }
            else {
                WWError(response.message)
            }
            
            if (self.menuTab?.mj_header.isRefreshing)! {
                self.menuTab?.mj_header.endRefreshing()
            }
            self.menuTab?.mj_footer.endRefreshingWithNoMoreData()
            self.hideLoadingView()
            if self.itemArray.count > 3{
                self.tableviewHeight = 3 * 103
                //self.frame = CGRect(x: 0, y: 0, width: SCREEN_WIDTH*0.9, height: 5 * 50)
            }else{
                self.tableviewHeight = CGFloat(self.itemArray.count) * 103
                //self.frame = CGRect(x: 0, y: 0, width: Int(SCREEN_WIDTH*0.9), height: self.itemArray.count * 50)
            }
            
        }
    }
    private func hideLoadingView() {
        self._loadingView?.removeFromSuperview()
    }
    private func getNextPage(){
        if self.itemArray.count <= 25 {
            self.menuTab?.mj_footer.endRefreshingWithNoMoreData()
            return
        }
        self.currentPage += 1
        ProjectListNetWork.projectList(pageIndex: self.currentPage, pageSize: 25, keyword: "", isShowApplying: false) { (response) in
            if response.success {
                if response.value!.count <= 0 {
                    self.menuTab?.mj_footer.endRefreshingWithNoMoreData()
                    return
                }
                self.itemArray += response.value!
                self.menuTab?.reloadData()
                self.menuTab?.mj_footer.endRefreshing()
            }
            else {
                WWError(response.message)
            }
        }
    }
    /*
     menu 弹出菜单的方法
     */
    func popupMenu(orginPoint:CGPoint){
        
        if self.isShow == true {
            return
        }
        self.isShow = true
        self.isHidden = false
        menuTab?.isHidden = false
        self.frame.origin = orginPoint
        self.menuTab?.reloadData()
        self.superview?.bringSubview(toFront: self)
        menuTab?.frame.size.height = 0.0
        /**
         这里是 弹出的动画
         */
        UIView.animate(withDuration: 0.2, animations: {
            
            self.frame.size.height = self.tableviewHeight ?? 0//(self.menuSize!.height)
            self.menuTab?.frame.size.height = self.tableviewHeight ?? 0//(self.menuSize!.height)
            
        }) { (finish) in
        }
    }
    /**
     这里是收回菜单的方法
     */
    
    func packUpMenu() {
        
        if self.isShow == false {
            return
        }
        self.isShow = false
        
        UIView.animate(withDuration: 0.2, animations: {
            
            self.menuTab?.frame.size.height = 0.0
            self.frame.size.height = 0.0
            
        }) { (finish) in
            
            self.isHidden = true
            self.menuTab?.isHidden = true
        }
    }
    
   
   

}
extension DropDownMenu:UITableViewDelegate,UITableViewDataSource{
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        
        return self.itemArray.count
    }
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell{
        
        let cell : LCProjectCell = tableView.dequeueReusableCell(withIdentifier: "LCProjectCell") as! LCProjectCell
         cell.setupDataWith(model: self.itemArray[indexPath.row])
        return cell
    }
    
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat{
        return 103
    }
    
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath){
        
        tableView.deselectRow(at: indexPath, animated: true)
        /**
         这里是把 选中的 indexPath 传值出去 ， 关闭menu列表
         */
      let  model : LCProjectListModel = self.itemArray[indexPath.row]
        self.didSelectIndex!(model)
        if (self.didSelectIndex != nil) {
            //self.didSelectIndex!(model)
        
        //self.getProjectListData()
        self.packUpMenu()
        ProjectListNetWork.updateSeletedState(model.MarketSupplyBaseID!, completionHandler: { (response) in
            if response{
                
                self.getProjectListData()
            }
        })
       }
    }
}
